package com.simple.mrchip.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.simple.mrchip.core.HttpAccess;
import com.simple.mrchip.core.HttpAccessListener;

import java.security.cert.TrustAnchor;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link AttendFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link AttendFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AttendFragment extends Fragment implements HttpAccessListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    // TODO: Rename and change types of parameters
    private Button mAttendButton;
    private TextView mInfoText;
    private SharedPreferences sharedPreferences;
    private OnFragmentInteractionListener mListener;
    private String mUUID;
    private boolean mbAttend;
    private HttpAccess httpAccess;
    private float mAttendTime;
    private float mLeaveTime;
    public AttendFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment AttendFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AttendFragment newInstance(String param1, String param2) {
        AttendFragment fragment = new AttendFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String attendDate = sharedPreferences.getString("AttendDate", "");
            String leaveDate = sharedPreferences.getString("LeaveDate", "");
            switch (msg.what) {
                case 0:
                    mAttendButton.setText("Leave");
                    if (!attendDate.isEmpty()) {
                        mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:");
                    }
                    break;
                case 1:
                    if (!attendDate.isEmpty() && !leaveDate.isEmpty()) {
                        mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:"+leaveDate);
                    }
                    break;
                case 2:

                    if (!attendDate.isEmpty() && !leaveDate.isEmpty()) {
                        mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:"+leaveDate);
                    }
                    mAttendButton.setClickable(false);
                    mAttendButton.setEnabled(false);
                    Toast.makeText(getContext(), "No Additional Leave Opportunity", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        httpAccess = HttpAccess.getInstance();
        httpAccess.setResponser("Attend", this);
        httpAccess.setResponser("Leave", this);
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        mUUID = sharedPreferences.getString("UUID", "");
        mbAttend = false;

        if (mUUID.isEmpty()) {
            Toast.makeText(getContext(), "UUID is Empty.", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(getActivity(), AppActivity.class);
            startActivity(intent);
            getActivity().finish();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_attend, container, false);
        mAttendButton = view.findViewById(R.id.btAttend);
        mInfoText = view.findViewById(R.id.txtAttendTime);
        long time = sharedPreferences.getLong("AttendTime", 0);
        System.out.println(time);
        if (time > 0) {
            long now = new Date().getTime();
            now = now / (3600 * 24 *1000);
            time = time / (3600 * 24 *1000);
            if(now == time) {
                mbAttend = true;
                mAttendButton.setText("Leave");
                String attendDate = sharedPreferences.getString("AttendDate", "");
                String leaveDate = sharedPreferences.getString("LeaveDate", "");
                if (!attendDate.isEmpty() && !leaveDate.isEmpty()) {
                    mInfoText.setText("AttendTime:"+attendDate+"\nLeaveTime:"+leaveDate);
                }
                int count = sharedPreferences.getInt("LeaveTime", 0);
                if (count > 3) {
                    mAttendButton.setClickable(false);
                    mAttendButton.setEnabled(false);
                }
            }
        }
        mAttendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mbAttend) {
                    httpAccess.leave(mUUID);
                } else {
                    httpAccess.attend(mUUID);
                }
            }
        });
        return view;
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void getHttpData(String response) {
        if (response.equals("Error")) {
            Toast.makeText(getContext(), "Attend Error", Toast.LENGTH_SHORT).show();
            return;
        }
        if (response.equals("Exist")) {
            mbAttend = true;
            handler.sendEmptyMessage(0);
            return;
        }
        if (mbAttend) {
            int count = sharedPreferences.getInt("LeaveTime", 0);
            if(count > 3) {
                handler.sendEmptyMessage(2);
                return;
            }
            mLeaveTime = Float.valueOf(response);
            Calendar calender = Calendar.getInstance(Locale.CHINA);
            calender.setTimeInMillis((long)(mLeaveTime * 1000));
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putInt("LeaveTime", ++count);
            editor.putString("LeaveDate", DateFormat.format("dd-MM-yyyy hh:mm:ss", calender).toString());
            editor.apply();
            handler.sendEmptyMessage(1);
        }
        if(!mbAttend) {
            Date date = new Date();
            long time = date.getTime();
            mAttendTime = Float.valueOf(response);
            Calendar calender = Calendar.getInstance(Locale.CHINA);
            calender.setTimeInMillis((long)(mAttendTime * 1000));

            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putLong("AttendTime", time);
            editor.putInt("LeaveTime", 0);
            editor.putString("AttendDate", DateFormat.format("dd-MM-yyyy hh:mm:ss", calender).toString());
            editor.apply();
            mbAttend = true;
            handler.sendEmptyMessage(0);
        }

        System.out.println(response);
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
